package com.yyw.springboot02web.controller;

import com.yyw.springboot02web.dao.DepartmentDao;
import com.yyw.springboot02web.dao.EmployeeDao;
import com.yyw.springboot02web.entities.Department;
import com.yyw.springboot02web.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * @ClassName CustomersController
 * @Description TODO
 * @Author YiYuWei
 * @Date 2020/6/27 12:16
 * @Version 1.0
 */
@Controller
public class CustomersController {
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private EmployeeDao employeeDao;

    @GetMapping("/emps")
    public String list(Model model){
        Collection<Employee> all = employeeDao.getAll();
        model.addAttribute("emps",all);
        return "emp/list";
    }

    @GetMapping("/emp")
    public String doadd(Model model){
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("dept",departments);
        return "emp/add";
    }

    @PostMapping("/emp")
    public String add(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @GetMapping("/emp/{id}")
    public String doedit(@PathVariable("id") Integer id,Model model){
        Employee employee = employeeDao.get(id);
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("dept",departments);
        model.addAttribute("emp",employee);
        return "emp/add";
    }

    @PutMapping("/emp")
    public String update(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @DeleteMapping("/emp/{id}")
    public String delete(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
